﻿using System;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Net;
using Microsoft.TeamFoundation.Client;

namespace TeamFoundationServerSensor {

    /// <summary>
    /// A class used to return an SQL connection or fail gracefully.
    /// </summary>
    public static class Connections {

        /// <summary>
        /// A method to quickly get an active sql connection from the
        /// VSTFS server.
        /// </summary>
        /// <param name="catalog">The initial catalog to connect to.</param>
        /// <returns>An active sqlconnection if possible.</returns>
        public static SqlConnection getNewSQLConnection(string catalog) {

            // Determine whether we are going to use local login or a predefined
            // username and password.
            if (Settings.Instance.getSettingBoolean("UseWindowsSQLLogin")) {
                return new SqlConnection("Data Source=" 
                    + Settings.Instance.getSetting("Server") 
                    + ";Initial Catalog=" + catalog 
                    + ";Integrated Security=SSPI");
            }
            else {
                return new SqlConnection("Data Source=" 
                    + Settings.Instance.getSetting("Server") 
                    + ";Initial Catalog=" + catalog
                    + ";User ID=" + Settings.Instance.getSetting("TFSUser")
                    + ";Password='" + Settings.Instance.getSetting("TFSPassword") 
                    + "';");
            }
        }

        /// <summary>
        /// Attempts to return a brand new connection to the team foundation
        /// server.
        /// </summary>
        /// <returns>A connection to the team foundation server or null.</returns>
        public static TeamFoundationServer getNewTFSConnection() {

            // Create a new instance of the TFS server using standard login.
            NetworkCredential cred = new NetworkCredential(Settings.Instance.getSetting("TFSUser"),
                Settings.Instance.getSetting("TFSPassword"));
            TeamFoundationServer tfs = new TeamFoundationServer(
                Settings.Instance.getSetting("Server"), cred);

            // Attempt to autheticate with the server.
            try {
                tfs.EnsureAuthenticated();
            }
            catch (Exception e) {
                Logger.TheInstance.Log(e);
            }

            // Return the instance if authentication has worked correctly
            // otherwise pass null.
            if (tfs != null && tfs.HasAuthenticated) {
                return tfs;
            }
            else {
                return null;
            }
        }
    }
}
